import { Group, Mesh, MeshStandardMaterial } from 'three'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'
import {
  frameColorTexture,
  frameDispTexture,
  frameRoughTexture,
} from './Ttextures'

const objLoader = new OBJLoader()

//加载obj模型
export const pikachiuPromise = new Promise((resolve, reject) => {
  objLoader
    .loadAsync('/pikachiu.obj')
    .then((group) => {
      const frame = group.children[0]
      if (frame instanceof Mesh) {
        frame.material.dispose()
        // 添加材质
        frame.material = new MeshStandardMaterial({
          map: frameColorTexture, //颜色材质
          roughness: frameRoughTexture, //粗糙材质
          bumpMap: frameDispTexture, //凹凸材质
        })
      }
      // frame.position.z = 20
      resolve(frame)
    })
    .catch((err) => {
      reject(err)
    })
})

// 函数形式返回promise
export const getFrame = async function () {
  const group = await objLoader.loadAsync('/pikachiu.obj')
  if (group instanceof Group) {
    const frame = group.children[0]
    if (frame instanceof Mesh) {
      frame.material.dispose()
      // 添加材质
      frame.material = new MeshStandardMaterial({
        map: frameColorTexture, //颜色材质
        roughnessMap: frameRoughTexture, //粗糙材质
        bumpMap: frameDispTexture, //凹凸材质
      })
    }
    frame.position.z = 20
    return frame
  } else {
    console.error(group)
    return null
  }
}
